<!--页面交互逻辑不复杂的弹出选择框-->
<template>
  <div class="divandpro">
    <j-modal
      :title="name"
      width="70%"
      :visible="display"
      switchFullscreen
      :confirmLoading="confirmLoading"
      @cancel="close"
      @select="handleOk()"
      cancelText="关闭">
      <template slot="footer">
        <a-button @click="close" :loading="confirmLoading">取消</a-button>
        <a-button type="primary" @click="handleOk" :loading="confirmLoading">确认</a-button>
      </template>
      <!--        <div id="movebox"   @click="handleMove(e)"  class="movebox">-->
      <a-row :gutter="18" :spinning="confirmLoading">
        <a-col :span="24">
          <!-- 查询区域 -->
<!--          <div class="table-page-search-wrapper">-->
<!--            <a-form layout="inline" @keyup.enter.native="searchQuery">-->
<!--              <a-row :gutter="18">-->
<!--                <a-col :xl="8" :lg="7" :md="2" :sm="18" v-for="(item,index) in formconfig" :key="index">-->
<!--                  <a-form-item :label=item.label>-->
<!--                    <a-input :placeholder="'请输入' + item.label" v-model="queryParam[item.key]"></a-input>-->
<!--                  </a-form-item>-->
<!--                </a-col>-->
<!--                <div style="float: right;overflow: hidden;" class="table-page-search-submitButtons">-->
<!--                  <a-col :xl="6" :lg="7" :md="2" :sm="24">-->
<!--                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>-->
<!--                    <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>-->
<!--                  </a-col>-->
<!--                </div>-->
<!--              </a-row>-->
<!--            </a-form>-->
<!--          </div>-->
          <div v-if="name=='添加货补商品'">本单可用货补金额：1200元,本单已选货补金额：1200元</div>
          <div v-if="name=='添加赠品'">本单可用货补金额：1200元</div>
          <a-table
            size="middle"
            class='Table'
            bordered
            :rowKey="rowKey"
            :columns="innerColumns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :scroll="{y: 240 }"
            :rowSelection="{selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox':'radio',columnWidth:columW}"
            :customRow="customRowFn"
            @change="handleTableChange">
          </a-table>
        </a-col>
        <!--        <a-col :span="8">-->
        <!--          <a-card :title="'已选' + name" :bordered="false" :head-style="{padding:0}" :body-style="{padding:0}">-->
        <!--            <a-table size="middle" :rowKey="rowKey" bordered v-bind="selectedTable" :columns="innerColumns">-->
        <!--              <span slot="action" slot-scope="text, record, index">-->
        <!--                <a @click="handleDeleteSelected(record, index)">删除</a>-->
        <!--              </span>-->
        <!--            </a-table>-->
        <!--          </a-card>-->
        <!--        </a-col>-->
      </a-row>
    </j-modal>
  </div>
</template>

<script>
  import { Cascader } from 'ant-design-vue'
  import Ellipsis from '@comp/ellipsis'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import { cloneObject, pushIfNotExist } from '@/utils/util'
  import lodash from 'lodash'
  import { getAction, postAction } from '@api/manage'
  import { filterObj } from '@/utils/util'

  export default {
    name: 'proChose',
    mixins: [PageListMixin],
    components: { Ellipsis, Cascader },

    props: {
      value: {
        type: Array,
        default: () => []
      },
      checkVal: {
        type: Function | Object
      },
      visible: {
        type: Boolean,
        default: false
      },
      // multiple: {
      //   type: Boolean,
      //   default: true
      // },
      width: {
        type: Number,
        default: 900
      },
      name: {
        type: String,
        default: '关联商品'
      },
      // 添加商品的回传

      // listUrl: {
      //   type: String,
      //   required: true,
      //   default: ''
      // },
      // 根据 value 获取显示文本的地址，例如存的是 userName，可以通过该地址获取到 realName
      valueUrl: {
        type: String,
        default: ''
      },
      displayKey: {
        type: String,
        default: null
      },
      // columns: {
      //   type: Array,
      //   required: true,
      //   default: () => []
      // },
      // 查询条件Code
      queryParamCode: {
        type: String,
        default: null
      },
      // 查询条件文字
      queryParamText: {
        type: String,
        default: null
      },
      // rowKey: {
      //   type: String,
      //   default: 'id'
      // },
      // 过长裁剪长度，设置为 -1 代表不裁剪
      ellipsisLength: {
        type: Number,
        default: 12
      }
    },
    data() {
      return {
        rowKey: '',
        columW: 4,
        confirmLoading:false,
        multiple: true,
        display: false,
        columns: [],
        valueKey: '',
        innerColumns: [],
        innerValue: [],
        // 已选择列表
        selectedTable: {
          pagination: false,
          scroll: { y: 240 },

          dataSource: []
        },
        renderEllipsis: (value) => (<ellipsis length={this.ellipsisLength}>{value}</ellipsis>),
        url: {
          list: null,
          addCart:window._CONFIG['domianDmsURL'] + '/order/dmsOrderHead/addShopping',
          // treedata: window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/getProductTypeTree'
        },
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 5,
          pageSizeOptions: ['5', '10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        options: [],
        dataSourceMap: {},
        formconfig: [],
        tableconfig: {},
        status: null,
        status2: null,
        isorter: {}
      }
    },
    watch: {
      'checkVal': {
        deep: true,
        immediate: true,
        handler(val) {
          this.$nextTick(() => {
            if (val && !lodash.isEmpty(val)) this.$set(this, 'queryParam', val)
          })
        }
      },
      value: {
        deep: true,
        immediate: true,
        handler(val) {
          this.$nextTick(() => {
            this.innerValue = cloneObject(val)
            this.selectedRowKeys = []
            this.valueWatchHandler(val)

            // this.queryOptionsByValue(val)
          })
        }
      },
      // dataSource: {
      //   deep: true,
      //   handler(val) {
      //     this.emitOptions(val)
      //     this.valueWatchHandler(this.innerValue)
      //   }
      // },
      selectedRowKeys: {
        immediate: true,
        deep: true,
        handler(val) {
          this.selectedTable.dataSource = val.map(key => {
            for (let data of this.dataSource) {
              if (data[this.rowKey] === key) {
                pushIfNotExist(this.innerValue, data[this.valueKey])
                return data
              }
            }
            for (let data of this.selectedTable.dataSource) {
              if (data[this.rowKey] === key) {
                pushIfNotExist(this.innerValue, data[this.valueKey])
                return data
              }
            }
            console.warn('未找到选择的行信息，key：' + key)
            return {}
          })
        }
      }
    },
    methods: {
      logsdisappear(code) {
        console.log(code)
      },
      // 级联选择器多选

      // 重置数据
      searchReset() {
        this.queryParam = {}
        this.loadData(1)
      },
      getQueryParams() {
        //高级查询器  数据采集
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        let param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        console.log(param)
        param.field = this.getQueryField()
        param.current = this.ipagination.current
        param.size = this.ipagination.pageSize
        param.feeManageType=1
        delete param.birthdayRange //范围参数不传递后台
        return filterObj(param)
      },
      // 获取树状数据  status:name  status2:code  datasource, 回显的数组数据
      edit(formconfig, tableconfig, status, status2, datasource) {
        console.log(formconfig, tableconfig, status, status2, datasource)
        this.dataSource = []
        this.tableconfig = Object.assign({}, tableconfig)
        if (!this.url.list || this.url.list !== this.tableconfig.list) {
          this.url.list = this.tableconfig.list
          this.queryParam = {}
          this.loadData()
        } else {
          this.loadData()
        }
        this.formconfig = JSON.parse(JSON.stringify(formconfig))
        this.innerColumns = this.tableconfig.columns
        this.$nextTick(() => {
          this.multiple = tableconfig.multiple
          tableconfig.columW ? this.columW = tableconfig.columW : this.columW = 4
        })
        if (datasource && datasource.length !== 0) {
          this.selectedRowKeys = datasource.map(item => {
            return item[this.rowKey]
          })
          this.selectionRows = datasource
        }
        if (status || status == 0) {
          this.status = status
          this.status2 = status2
        }
        this.display = true
      },

      // 需要带值查询事件
      searchData(){

      },
      /** 关闭弹窗 */
      close() {
        this.display = false
      },

      valueWatchHandler(val) {
        val.forEach(item => {
          this.dataSource.concat(this.selectedTable.dataSource).forEach(data => {
            if (data[this.valueKey] === item) {
              pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
            }
          })
        })
      },
      getParams() {
        const params = this.checkVal || {}
        for (let key of Object.keys(params)) {
          if (key && (params[key] === undefined || params[key] === '')) {
            return false
          }
        }
        return this.lodash.isEmpty(params) ? true : params
      },

      queryOptionsByValue(value) {
        console.log(this)
        const params = this.getParams()
        if (!params) return
        if (typeof params === 'boolean' && params) {
          if (!value || value.length === 0) {
            return
          }
          // 判断options是否存在value，如果已存在数据就不再请求后台了
          let notExist = false
          for (let val of value) {
            let find = false
            for (let option of this.options) {
              if (val === option.value) {
                find = true
                break
              }
            }
            if (!find) {
              notExist = true
              break
            }
          }
          if (!notExist) return
        }
        postAction(this.url.list, {
          // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
          // [this.valueKey]: value.join(',') + ',',
          pageNo: 1,
          pageSize: value.length,
          ...params
        }).then((res) => {
          if (res.success) {
            let dataSource = res.result
            if (!(dataSource instanceof Array)) {
              dataSource = res.result.records
            }
            this.emitOptions(dataSource, (data) => {
              pushIfNotExist(this.innerValue, data[this.valueKey])
              pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
              pushIfNotExist(this.selectedTable.dataSource, data, this.rowKey)
            })
          }
        })
      },

      emitOptions(dataSource, callback) {
        dataSource.forEach(data => {
          let key = data[this.valueKey]
          this.dataSourceMap[key] = data
          pushIfNotExist(this.options, { label: data[this.displayKey], value: key }, 'value')
          typeof callback === 'function' ? callback(data) : ''
        })
        this.$emit('options', this.options, this.dataSourceMap)
      },
// 鼠标移动事件

      /** 完成选择 */
      // handleOk() {
      //   let selectionRows = JSON.parse(JSON.stringify(this.selectionRows))
      //   this.$emit('okbro', selectionRows, this.status, this.status2)
      //   this.selectedTable.dataSource = []
      //   this.selectedRowKeys = []
      //   this.selectionRows = []
      //   this.isorter = {}
      //   this.close()
      // },
      async handleOk(rows) {
        let selectionRows = JSON.parse(JSON.stringify(this.selectionRows))
        if (rows) {
          let {
            detail
          } = this
          let _this=this
          let params = {
            id: this.formconfig.id,
            itemChangeEntityList: selectionRows.map(detail => {
              return {
                productCode: detail.productCode || detail.goodsCode,
                productName: detail.productName,
                goodsCode: detail.goodsCode || detail.productCode,
                goodsName: detail.goodsName,
                originalPrice: detail.originalPrice,
                dataType: '1',
                quantity: detail.quantity||1
              }
            })
          }
          this.confirmLoading = true
          console.log(this.confirmLoading)
          let res = await postAction(this.url.addCart, params)
          if (res.success) {
            // this.dataUpdata(res)
              this.$emit('ok', res, this.status, this.status2)

          } else {
            this.$message.error(res.message)
          }
          this.confirmLoading = false
          console.log(this.confirmLoading)
          this.close()
        }
      },
      /** 删除已选择的 */
      handleDeleteSelected(record, index) {
        this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
        this.selectionRows.splice(this.selectionRows.indexOf(record), 1)
        this.selectedTable.dataSource.splice(index, 1)
      },

      customRowFn(record) {
        return {
          on: {
            click: () => {
              console.log(this.rowKey)
              let key = record[this.rowKey]
              if (!this.multiple) {
                this.selectedRowKeys = [key]
                this.selectionRows = [record]
                // this.selectedTable.dataSource = [record]
              } else {
                let index = this.selectedRowKeys.indexOf(key)
                if (index === -1) {
                  this.selectedRowKeys.push(key)
                  this.selectionRows.push(record)
                  // this.selectedTable.dataSource.push(record)
                } else {
                  this.handleDeleteSelected(record, index)
                }
              }
            }
          }
        }
      },
      loadData(arg) {
        if (!this.url || !this.url.list) {
          // this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }

        let params = this.getQueryParams()//查询条件
        this.loading = true
        // if(['/isys','/isystem'].some(path=> new RegExp(`^${path}`).test(this.$route.fullPath))){
        //   getJSON(this.$route.fullPath).then((res) => {
        //     if (res.success) {
        //       this.dataSource = res.result.records;
        //       this.ipagination.total = res.result.total;
        //     }
        //     if(res.code===510){
        //       this.$message.warning(res.message)
        //     }
        //     this.loading = false;
        //   })
        // }else{
        let request = null
        let isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.url.list))
        if (isNoPagnation) {
          request = getAction
        } else {
          request = postAction
        }
        var that = this

        params.ways == 'get' ? request = getAction : request = postAction
        return request(this.url.list, params).then((res) => {
          if (res.success) {
            that.dataSource = isNoPagnation ? res.result : res.result.records
            res.result.records ? this.dataSource = res.result.records : this.dataSource = res.result
            if (!isNoPagnation) that.ipagination.total = res.result.total || 0
          } else {
            that.$message.warning(res.message)
          }
          that.loading = false
        })
        // }
      }

    }

  }
</script>

<style scoped lang="less">
  .divandpro {
    display: flex;
    flex-direction: row;


    .buttonadd {
      margin: 2px 0 0 15px;
      box-shadow: 0 0 3px 3px rgb(205, 205, 205);
      height: 40px;
      width: 40px;
    }

    .buttonadd:hover {
      box-shadow: 0 0 5px 5px rgb(205, 205, 205);
    }

    .addsadd {
      transform: translateX(-4px);
    }
  }

  .productlog {
    width: 90%;
    color: red;
    border: 1px solid rgb(205, 205, 205);
    padding: 2px 0 2px 4px;
    border-radius: 5px;
    box-sizing: border-box;
  }

  .productlog:hover {
    border: 1px solid rgb(2, 14, 225);

  }

</style>